/*
 * @Description: 封装常用的cesium场景效果
 * @Author: Daniel
 * @version:
 * @Date: 2023-12-18 15:03:28
 * @LastEditors: your name
 * @LastEditTime: 2024-04-25 14:36:18
 */
import * as Cesium from "cesium"
import { TencentImageryProvider } from "./mapPlugin";

// 初始化地图场景
export const initViewer = (container) => {
  // 初始化cesium地图对象viewer
  const viewer = new Cesium.Viewer(container, {
    timeline: false, // 是否显示时间线控件
    animation: false, // 是否显示动画控件
    baseLayerPicker: false, // 避免token
    infoBox: false, // 是否显示点击要素之后显示的信息
    selectionIndicator: false, //选中元素显示,默认true
    skyAtmosphere: false, //关闭地球光环
    homeButton: false,
    fullscreenButton: false,
    geocoder: false,
    sceneModePicker: false,
    shouldAnimate: true,
    navigationHelpButton: false,
    // 指定上下文
    contextOptions: {
      // 支持使用老版本webgl进行着色器编写
      requestWebgl1: true,
      // 开启纹理采样异性过滤，不开的话，视角越倾斜，越模糊
      allowTextureFilterAnisotropic: true,
      webgl: {
        alpha: false,
        depth: true,
        stencil: false,
        antialias: true,
        powerPreference: "high-performance",
        premultipliedAlpha: true,
        preserveDrawingBuffer: false,
        failIfMajorPerformanceCaveat: false,
      },
    },
  });
  // 使用cesium-map插件中的provider来进行加载
  const tencentImageryProvider = new TencentImageryProvider({
    style: 4,
    crs: "WGS84",
  });
  viewer.imageryLayers.addImageryProvider(tencentImageryProvider);

  return viewer;
};

// 设置地图场景
export const setScene = (viewer) => {
  //隐藏太阳
  viewer.scene.sun.show = false;
  //隐藏月亮
  viewer.scene.moon.show = false;
  viewer.scene.globe.enableLighting = true; // 开启全球光照

  // 泛光设置
  const bloom = viewer.scene.postProcessStages.bloom;
  bloom.enabled = false;

  // 亮度设置
  // 亮度设置
  var stages = viewer.scene.postProcessStages;
  viewer.postProcessStages.fxaa.enabled = true;
  viewer.scene.brightness =
    viewer.scene.brightness ||
    stages.add(Cesium.PostProcessStageLibrary.createBrightnessStage());
  viewer.scene.brightness.enabled = true;
  viewer.scene.brightness.uniforms.brightness = 1.2;
  viewer.scene.globe.depthTestAgainstTerrain = true;
  viewer._cesiumWidget._creditContainer.style.display = "none";

  viewer.shadows = true; //开启阴影效果
  viewer.shadowMap.darkness = 0.8; //阴影透明度--越大越透明
  //去cesium logo水印 或 css
  viewer.cesiumWidget.creditContainer.style.display = "none"; //去cesium logo水印
};

// 3dtiles模型加载
export const setTileset = (viewer, url, loadCb) => {
  // 添加白膜
  const tileset = viewer.scene.primitives.add(
    new Cesium.Cesium3DTileset({ url })
  );
  // 3dtiles加载完成的回调
  tileset.readyPromise.then(() => {
    tileset.style = new Cesium.Cesium3DTileStyle({
      color: {
        conditions: [["true", "color('rgba(36, 172, 242,0.9)',1)"]],
      },
    });
    // 默认飞行到3dtiles的包围盒处
    const boundingSphere = tileset.boundingSphere;
    viewer.camera.flyToBoundingSphere(boundingSphere, {
      duration: 2,
      maximumHeight: 1000,
    });
    loadCb(tileset);
  });
};
